package com.leyou.auth.service.impl;

import com.leyou.auth.config.JwtProperties;
import com.leyou.auth.service.UserAuthService;
import com.leyou.common.constants.RedisConstants;
import com.leyou.common.constants.UserTokenConstants;
import com.leyou.common.entity.Payload;
import com.leyou.common.entity.UserInfo;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.CookieUtils;
import com.leyou.common.utils.JwtUtils;
import com.leyou.user.client.UserClient;
import com.leyou.user.dto.UserDTO;
import feign.FeignException;
import io.jsonwebtoken.JwtException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * @author 虎哥
 */
@Service
public class UserAuthServiceImpl implements UserAuthService {

    private final UserClient userClient;

    private final JwtProperties prop;

    private final StringRedisTemplate redisTemplate;

    public UserAuthServiceImpl(UserClient userClient, JwtProperties prop, StringRedisTemplate redisTemplate) {
        this.userClient = userClient;
        this.prop = prop;
        this.redisTemplate = redisTemplate;
    }

    @Override
    public void login(String username, String password, HttpServletResponse response) {
        // 1.授权中心携带用户名密码，到用户中心查询用户
        try {
            UserDTO user = userClient.queryUserByUsernameAndPassword(username, password);

            // 2.校验查询结果
            if (user == null) {
                throw new LyException(400, "用户名或密码错误！");
            }

            // 3.如果正确，生成JWT凭证，查询错误则返回400
            // 3.1.准备用户信息
            UserInfo userInfo = new UserInfo(user.getId(), user.getUsername());
            // 3.2.准备JTI
            String jti = JwtUtils.createJTI();
            // 3.3.生成token
            String token = JwtUtils.generateTokenWithJTI(userInfo, jti, prop.getPrivateKey());

            // 4.把token的JTI存入redis，以userId为key 以JTI为value存入redis，并设置有效期30分钟
            redisTemplate.opsForValue().set(RedisConstants.JTI_KEY_PREFIX + user.getId(), jti,
                    RedisConstants.TOKEN_EXPIRE_MINUTES, TimeUnit.MINUTES);


            // 5.把JWT写入用户cookie
            writeCookie(response, token);

        } catch (FeignException e) {
            // 把远程调用异常转换抛出
            throw new LyException(e.status(), e.contentUTF8());
        }
    }

    public String verifyUser(HttpServletRequest request) {
        // 1.读取cookie
        String token = CookieUtils.getCookieValue(request, UserTokenConstants.COOKIE_NAME);
        // 2.获取token信息
        Payload<UserInfo> payload;
        try {
            payload = JwtUtils.getInfoFromToken(token, prop.getPublicKey(), UserInfo.class);
        } catch (Exception e) {
            // 抛出异常，证明token无效，直接返回401
            throw new LyException(401, "登录失效");
        }
        UserInfo userInfo = payload.getUserInfo();
        // 3.验证tokenId
        String key = RedisConstants.JTI_KEY_PREFIX + userInfo.getId();
        String cacheJTI = redisTemplate.opsForValue().get(key);
        if (!StringUtils.equals(cacheJTI, payload.getId())) {
            // token的id不符合，证明token无效，直接返回401
            throw new LyException(401, "登录失效");
        }
        // 4.返回用户
        return userInfo.getUsername();
    }

    public void logout(HttpServletRequest request, HttpServletResponse response) {
        // 1.获取用户cookie
        String token = CookieUtils.getCookieValue(request, UserTokenConstants.COOKIE_NAME);
        // 2.校验cookie中的token的有效性
        Payload<UserInfo> payload = null;
        try {
            payload = JwtUtils.getInfoFromToken(token, prop.getPublicKey(), UserInfo.class);
        } catch (Exception e) {
            // 3.如果无效，什么都不做
            return;
        }
        // 4.如果有效，删除cookie（重新写一个cookie，maxAge为0）
        CookieUtils.deleteCookie(UserTokenConstants.COOKIE_NAME, UserTokenConstants.DOMAIN, response);

        // 5.删除redis中的JTI
        // 5.1.获取用户信息
        UserInfo userInfo = payload.getUserInfo();
        // 5.2.删除redis数据
        redisTemplate.delete(RedisConstants.JTI_KEY_PREFIX + userInfo.getId());
    }


    private void writeCookie(HttpServletResponse response, String token) {
        Cookie cookie = new Cookie(UserTokenConstants.COOKIE_NAME, token);
        // cookie的作用域
        cookie.setDomain(UserTokenConstants.DOMAIN);
        // 是否禁止JS操作cookie，避免XSS攻击
        cookie.setHttpOnly(true);
        // cookie有效期，-1就是跟随当前会话，浏览器关闭就消失
        cookie.setMaxAge(-1);
        // cookie作用的路径，/代表一切路径
        cookie.setPath("/");
        response.addCookie(cookie);
    }
}
